package org.boyan.transcode;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.boyan.common.util.UUIDGenerator;
import org.boyan.entity.trans.TransCode;
import org.boyan.utils.ExcelUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class ExcelToTransCode {

    //传入文件并将excel文件转换为List<TransCode>
    public static List<TransCode> getTransCodeList(Object fileObject){
        Workbook workbook=null;
        if(fileObject instanceof MultipartFile){
            MultipartFile file= (MultipartFile) fileObject;
            workbook=ExcelUtils.getWorkBook(file);
        }else if(fileObject instanceof File){
            File file= (File) fileObject;
            workbook=ExcelUtils.getWorkBook(file);
        }
        List<TransCode> transCodeList=new ArrayList<>();
        try{
            Sheet sheet=workbook.getSheetAt(0);
            int rowNum=sheet.getLastRowNum();
            if(!"交易码".equals(sheet.getRow(0).getCell(1).getStringCellValue())){
                throw new Exception("文件导入错误");
            }
            for (int i = 1; i <= rowNum; i++) {
                TransCode transCode = new TransCode();
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue; //避免表格中存在空格
                }
                transCode.setTransCode(row.getCell(1).getStringCellValue());
                transCode.setId(UUIDGenerator.generate());
                transCodeList.add(transCode);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return removeDuplicate(transCodeList);
    }


    //List<TransCode>去重
    private static List<TransCode> removeDuplicate(List<TransCode> transCodeList){
        Set<TransCode> transCodeSet=new TreeSet<>((o1, o2) -> o1.getTransCode().compareTo(o2.getTransCode()));
        transCodeSet.addAll(transCodeList);
        return new ArrayList<>(transCodeSet);
    }
}
